import Vue from 'vue'
import {getToken} from "@/util/auth";
import request from "@/router/axios"

export function isStringEmpty(str) {
  if (isNull(str)) return true
  if (str === '') return true
  if (str.length === 0) return true
  return false
}

export function isStringBlank(str) {
  if (isStringEmpty(str)) return true
  if (isStringEmpty(str.trim())) return true
  return false
}

export function getSetStorageEntity(key, _value) {
  if (isNotNull(_value)) localStorage[key] = _value
  return localStorage[key]
}

export function isNull(obj) {
  return obj == null
}

export function isListEmpty(_list) {
  if (isNull(_list)) return true
  if (isNull(_list.length)) return true
  return _list.length === 0
}

export function listNotEmpty(_list) {
  return !isListEmpty(_list)
}

export function isMapEmpty(_map) {
  if (isNull(_map)) return true
  if (equals(JSON.stringify(_map), '{}')) return true
  return false
}

export function removeListDuplicate(_list, _key) {
  const re = []
  if (isListEmpty(_list)) return re
  const tmp = {}
  for (const item of _list) {
    if (isNull(_key)) {
      tmp[item] = item
    } else {
      tmp[item[_key]] = item
    }
  }
  Object.keys(tmp).forEach(k => {
    re.push(tmp[k])
  })
  return re
}

export function isNotNull(obj) {
  return obj != null
}

export function isBlank(obj) {

}

export function isTrue(obj) {
  return obj === true
}

export function isNotTrue(obj) {
  return obj !== true
}

export function isFalse(obj) {
  return equals(obj, false)
}

export function isObjectEmpty(obj) {
  return obj === '{}'
}

export function equals(objA, objB) {
  return objA === objB
}

export function strEquals(objA, objB) {
  return equals(String(objA), String(objB))
}

export function strEqualsIgnoreCase(objA, objB) {
  return equals(String(objA).toLowerCase(), String(objB).toLowerCase())
}

export function notEquals(objA, objB) {
  return objA !== objB
}

export function anyIsNull(...objs) {
  for (const v of objs) if (isNull(v)) return true
  return false
}

export function allIsNotNull(...objs) {
  for (const v of objs) if (isNull(v)) return false
  return true
}

export function equalsAny(objA, ...objB) {
  for (const v of objB) if (equals(objA, v)) return true
  return false
}

export class Timeout {
  constructor(_duration) {
    this.timeout = null
    this.duraion = isNull(_duration) ? 200 : _duration
  }

  handle(success) {
    this.clear()
    this.timeout = setTimeout(() => {
      success && success()
    }, this.duraion)
  }

  clear() {
    clearTimeout(this.timeout)
  }
}

// 格式话数据，添加逗号
export function formatNumberWithComma(v) {
  try {
    return (v || 0).toString().replace(/(\d)(?=(?:\d{3})+$)/g, '$1,')
  } catch (e) {
    console.error(e)
    return 'error'
  }
}

export function lastItem(_list) {
  if (isNull(_list)) return null
  if (isListEmpty(_list)) return null
  return _list[_list.length - 1]
}

export function firstItem(_list) {
  if (isNull(_list)) return null
  if (isListEmpty(_list)) return null
  return _list[0]
}

export function listContains(_list, _elem) {
  if (isListEmpty(_list)) return false
  for (const item of _list) {
    if (equals(item, _elem)) return true
  }
  return false
}

export function listRemove(_list, _delIndex) {
  if (isListEmpty(_list)) return
  if (_delIndex < 0) return
  if (_delIndex >= _list.length) return
  _list.splice(_delIndex, 1)
}

export function listAddFirst(_list, _elem) {
  if (isNull(_list)) return
  _list.unshift(_elem)
}

export function contains(_str, _subStr) {
  if (anyIsNull(_str, _str.indexOf)) return false
  return _str.indexOf(_subStr) >= 0
}

export function containsIgnoreCase(_str, _subStr) {
  return contains(_str.toLowerCase(), _subStr.toLowerCase())
}

export function containsAny(_str, ..._subStrList) {
  if (anyIsNull(_str, _str.indexOf)) return false
  for (const s of _subStrList) {
    if (_str.indexOf(s) >= 0) {
      return true
    }
  }
  return false
}

export function notContains(_str, _subStr) {
  return _str.indexOf(_subStr) === -1
}

export function isNumber(value) {
  return typeof value === 'number' && !isNaN(value)
}

export function isNumberValue(value) {
  return typeof value === 'number' && !isNaN(value)
}

export function readableDuration(_ms) {
  if (!isNumber(_ms)) return _ms

  const dSpan = 1000 * 60 * 60 * 24
  const hSpan = 1000 * 60 * 60
  const mSpan = 1000 * 60
  const sSpan = 1000

  if (_ms >= dSpan) {
    const d = toFixedValue(_ms / dSpan)
    const h = toFixedValue((_ms - d * dSpan) / hSpan)
    return d + 'd ' + h + 'h'
  }
  if (_ms >= hSpan) {
    const h = toFixedValue(_ms / hSpan)
    const m = toFixedValue((_ms - h * hSpan) / mSpan)
    return h + 'h ' + m + 'm'
  }
  if (_ms >= mSpan) {
    const m = toFixedValue(_ms / mSpan)
    const s = toFixedValue((_ms - m * mSpan) / sSpan)
    return m + 'm ' + s + 's'
  }
  if (_ms >= sSpan) {
    const s = toFixedValue(_ms / sSpan)
    const ms = toFixedValue(_ms - s * sSpan)
    return s + 's ' + ms + 'ms'
  }
  return toFixedValue(_ms) + 'ms'

  function toFixedValue(_v) {
    return Math.floor(_v).toFixed(0)
  }
}

export function colorHash(str, lsL, lsS) {
  lsL = typeof lsL !== 'undefined' ? lsL : [0.35, 0.5, 0.65]
  lsS = typeof lsS !== 'undefined' ? lsS : [0.35, 0.5, 0.65]
  const seed = 131
  const seed2 = 137
  let hash = 0
  str += 'x'
  const MAX_SAFE_INTEGER = parseInt(9007199254740991 / seed2)
  for (let i = 0; i < str.length; i++) {
    if (hash > MAX_SAFE_INTEGER) {
      hash = parseInt(hash / seed2)
    }
    hash = hash * seed + str.charCodeAt(i)
  }
  let H = hash % 359 // note that 359 is a prime
  hash = parseInt(hash / 360)
  const S = lsS[hash % lsS.length]
  hash = parseInt(hash / lsS.length)
  const L = lsL[hash % lsL.length]
  H /= 360
  const q = L < 0.5 ? L * (1 + S) : L + S - L * S
  const p = 2 * L - q
  const RGBArray = [H + 1 / 3, H, H - 1 / 3].map(function (color) {
    if (color < 0) {
      color++
    }
    if (color > 1) {
      color--
    }
    if (color < 1 / 6) {
      color = p + (q - p) * 6 * color
    } else if (color < 0.5) {
      color = q
    } else if (color < 2 / 3) {
      color = p + (q - p) * 6 * (2 / 3 - color)
    } else {
      color = p
    }
    return Math.round(color * 255)
  })
  let hex = '#'
  RGBArray.forEach(function (value) {
    if (value < 16) {
      hex += 0
    }
    hex += value.toString(16)
  })
  return hex
}

export function titleCase(str) {
  return str.slice(0, 1).toUpperCase() + str.slice(1).toLowerCase()
}


export function confirmWarning(_title, _content, success, cancel) {
  Vue.prototype.$confirm(_content, _title, {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    success && success()
  }).catch(() => {
    cancel && cancel()
  })
}

export function msgSuccess(msg) {
  Vue.prototype.$message({
    type: "success",
    message: msg || "操作成功!"
  });
}

export function msgError(_err) {
  Vue.prototype.$message({
    type: "error",
    message: _err
  });
}


export function getRespData(res) {
  return res.data.data
}

export function getTotal(res) {
  return getRespData(res).total
}

export function getRecords(res) {
  return getRespData(res).records
}

// 二进制流转换为base64 格式。要求 data 是blob格式
export function getBase64(data) {
  return new Promise((resolve, reject) => {
    const blob = new Blob([data], {type: "image/png"}); // 必须指定type类型
    const reader = new FileReader();
    reader.readAsDataURL(blob);
    reader.onload = () => resolve(reader.result);
    reader.onerror = (error) => reject(error);
  })
}

export function downloadBase64File(fileName, content) {
  let aLink = document.createElement('a')
  let blob = base64ToBlob(content) // new Blob([content]);
  let evt = document.createEvent('HTMLEvents')
  evt.initEvent('click', true, true)// initEvent 不加后两个参数在FF下会报错  事件类型，是否冒泡，是否阻止浏览器的默认行为
  aLink.download = fileName
  aLink.href = URL.createObjectURL(blob)
  aLink.click()

  function base64ToBlob(code) {
    let parts = code.split(';base64,')
    let contentType = parts[0].split(':')[1]
    let raw = window.atob(parts[1]) // 解码base64得到二进制字符串
    let rawLength = raw.length
    let uInt8Array = new Uint8Array(rawLength) // 创建8位无符号整数值的类型化数组
    for (let i = 0; i < rawLength; ++i) {
      uInt8Array[i] = raw.charCodeAt(i) // 数组接收二进制字符串
    }
    return new Blob([uInt8Array], {type: contentType})
  }
}

export function compressBase64(base64, w, callback) {
  var newImage = new Image();
  var quality = 0.6; //压缩系数0-1之间
  newImage.src = base64;
  newImage.setAttribute("crossOrigin", 'Anonymous'); //url为外域时需要
  var imgWidth, imgHeight;
  newImage.onload = function () {
    imgWidth = this.width;
    imgHeight = this.height;
    var canvas = document.createElement("canvas");
    var ctx = canvas.getContext("2d");
    if (Math.max(imgWidth, imgHeight) > w) {
      if (imgWidth > imgHeight) {
        canvas.width = w;
        canvas.height = w * imgHeight / imgWidth;
      } else {
        canvas.height = w;
        canvas.width = w * imgWidth / imgHeight;
      }
    } else {
      canvas.width = imgWidth;
      canvas.height = imgHeight;
      quality = 0.6;
    }
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.drawImage(this, 0, 0, canvas.width, canvas.height);
    var base64 = canvas.toDataURL("image/jpeg", quality); //压缩语句
    callback(base64); //必须通过回调函数返回，否则无法及时拿到该值
  }
}

export const downLoadFile = async (url, name) => {
  // Change this to use your HTTP client
  fetch(url, {headers: {'Uic-Auth': 'bearer ' + getToken()}}) // FETCH BLOB FROM IT
    .then((response) => {
      name = response.headers.get("content-disposition").split("filename=")[1];
      return response.blob();
    })
    .then((blob) => { // RETRIEVE THE BLOB AND CREATE LOCAL URL
      const _url = window.URL.createObjectURL(blob);
      let fileLink = document.createElement('a');
      fileLink.href = _url;
      fileLink.download = name;
      fileLink.click();
    }).catch((err) => {
    console.log(err);
  });
};

export const download = (url, params) => {
  return request({
    method: 'GET',
    responseType: "blob", // 这行配置可不能少
    url,
    params
  })
}

export const downloadFile2 = (url, params, name) => {
  return download(url, params)
    .then((res) => {
      const _url = window.URL.createObjectURL(res.data);
      let fileLink = document.createElement('a');
      fileLink.href = _url;
      fileLink.download = name;
      fileLink.click();
    }).catch(e => {
      console.error(e)
    })
}

// export function downLoadFile(url,name) {
//   let downloadElement = document.createElement('a');
//   downloadElement.href = url;
//   // 下载后文件名
//   downloadElement.download = name;
//   document.body.appendChild(downloadElement);
//   // 点击下载
//   downloadElement.click();
//   // 下载完成移除元素
//   document.body.removeChild(downloadElement);
//   // 释放掉blob对象
//   window.URL.revokeObjectURL(href);
// }
